import { DeleteModal } from '@/components/Modals';
import groupBaseApi from '@/pages/Organization/GroupBaseManagement/request';
import roleApi from '@/pages/Organization/RoleManagement/role-request';
import subsidiaryBaseApi from '@/pages/Organization/SubsidiaryBaseManagement/request';
import { createFilterColumns, createTableRequestParams } from '@/utils/table';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Space, Typography } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './Form';
import RoleModal from './Modal';

function RoleManagement() {
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const [isShowModal, setIsShowModal] = useState(false);
  const [isShowRoleModal, setIsShowRoleModal] = useState(false);
  const [curData, setCurData] = useState<Partial<RoleManagementApi.InfoResponse>>({});
  const [filterList] = useState<Requestor.FilterResponse[]>([]);

  const [groupBaseList, setGroupBaseList] = useState<GroupBaseManagementApi.InfoResponse[]>([]);
  const [subsidiaryBaseList, setSubsidiaryBaseList] = useState<
    SubsidiaryBaseManagementApi.InfoResponse[]
  >([]);

  const groupBaseOptions = useMemo(
    () => groupBaseList.map((item) => ({ label: item.groupName, value: item.id })),
    [groupBaseList],
  );
  const subsidiaryBaseListOptions = useMemo(
    () => subsidiaryBaseList.map((item) => ({ label: item.subsidiaryName, value: item.id })),
    [subsidiaryBaseList],
  );

  // request
  const getListRequest = (
    params: Requestor.TableParams,
    filterList: Requestor.FilterResponse[],
  ) => {
    const requestParams = createTableRequestParams(params, filterList);
    return roleApi.getList(requestParams);
  };
  const getList = async (params: Requestor.TableParams) => {
    return getListRequest(params, filterList);
  };
  const getAllGroupBaseList = async () => {
    const list = await groupBaseApi.getAllList();
    setGroupBaseList(list);
  };
  const getAllSubsidiaryBaseList = async () => {
    const list = await subsidiaryBaseApi.getSelectList(initialState?.userInfo?.id);
    setSubsidiaryBaseList(list);
  };

  useEffect(() => {
    getAllGroupBaseList();
    getAllSubsidiaryBaseList();
  }, []);

  // method
  const setRoleModal = (state: boolean, data?: RoleManagementApi.ListResponse) => {
    setCurData(data || {});
    setIsShowRoleModal(state);
  };
  const setRemoveModal = (state: boolean, data?: RoleManagementApi.ListResponse) => {
    setCurData(data || {});
    setIsShowModal(state);
  };
  const removeRequest = async (params: RoleManagementApi.DeleteParams) => {
    const data = await roleApi.remove(params);
    if (data.success) {
      actionRef.current?.reload();
      setRemoveModal(false);
    }
    if (data.success) {
      setRemoveModal(false);
    }
  };
  const onConfirmRemove = () => {
    const { id = '' } = curData;
    removeRequest([id]);
  };
  const onCancelRemove = () => {
    setRemoveModal(false);
  };
  const findData = (
    value: string,
    options: {
      label: string;
      value: string;
    }[],
  ) => {
    for (let item of options) {
      if (item.value === value) return item;
    }
    return { label: '', value: '' };
  };
  const columns = useMemo(() => {
    const filterColumns = createFilterColumns<RoleManagementApi.ListResponse>(filterList);
    const tableColumns: ProColumns<RoleManagementApi.ListResponse>[] = [
      {
        title: '角色名称',
        dataIndex: 'roleName',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '所属集团',
        dataIndex: 'groupID',
        ellipsis: true,
        align: 'center',
        render(_, record) {
          const data = findData(record.groupID, groupBaseOptions);
          return data?.label;
        },
      },
      {
        title: '所属子公司',
        dataIndex: 'subsidiaryID',
        ellipsis: true,
        align: 'center',
        render(_, record) {
          const data = findData(record.subsidiaryID, subsidiaryBaseListOptions);
          return data?.label;
        },
      },
      {
        title: '操作',
        hideInSearch: true,
        align: 'center',
        render(_, record) {
          return (
            <Space>
              <Typography.Link>
                <Button type="link" onClick={() => setRoleModal(true, record)}>
                  菜单权限
                </Button>
              </Typography.Link>
              <Typography.Link>
                <Form isEdit data={record} onSuccess={() => actionRef.current?.reload()} />
              </Typography.Link>
              <Typography.Link>
                <Button type="link" onClick={() => setRemoveModal(true, record)}>
                  删除角色
                </Button>
              </Typography.Link>
            </Space>
          );
        },
      },
    ];
    return filterColumns.concat(tableColumns);
  }, [filterList, groupBaseOptions, subsidiaryBaseListOptions]);
  return (
    <PageContainer>
      <ProTable
        bordered
        size="small"
        actionRef={actionRef}
        rowKey="id"
        headerTitle={false}
        search={false}
        options={false}
        toolBarRender={() => [
          <Button key="search" type="primary" onClick={() => actionRef.current?.reload()}>
            查询
          </Button>,
          <Form key="add" isEdit={false} onSuccess={() => actionRef.current?.reload()} />,
        ]}
        columns={columns}
        expandable={{ defaultExpandAllRows: true }}
        request={getList}
      />
      <DeleteModal
        open={isShowModal}
        content="确认删除吗？"
        onOk={onConfirmRemove}
        onCancel={onCancelRemove}
      />
      <RoleModal
        visible={isShowRoleModal}
        data={curData}
        onSuccess={() => setRoleModal(false)}
        onCancel={() => setRoleModal(false)}
      />
    </PageContainer>
  );
}

export default RoleManagement;
